﻿using K9Nano.Caching;
using K9Nano.Dependency;
using K9Nano.Serialization;
using K9Nano.Session;

namespace K9Nano.Resources;

public class ResourceManager(IUserContextAccessor userContextAccessor, ITypedCache<ResourceCache> cache) : IResourceManager, IScopedDependency
{
    public T? Get<T>(string id) where T : IResource
    {
        var resourceCache = cache.Get(id);
        if (resourceCache == null) return default;
        var result = JsonHelper.Deserialize<T>(resourceCache.Resource);
        if (result is null) return default;
        if(result.OwnerId is null && string.IsNullOrEmpty(result.Permission))
        {
            // 不做权限控制
            return result;
        }
        var currentUser = userContextAccessor.CurrentUser;
        if (currentUser?.UserId is null) return default;
        if (result.OwnerId == currentUser.UserId)
        {
            return result;
        }
        if (!string.IsNullOrEmpty(result.Permission)
            && currentUser.HasPermission(result.Permission))
        {
            return result;
        }
        // 无权访问
        return default;
    }

    public void Protect(IResource resource, TimeSpan expires)
    {
        var json = JsonHelper.Serialize(resource);
        cache.Add(resource.Id, new ResourceCache(resource.Id, json), absoluteTimeout: expires);
    }
}

public record ResourceCache(string Id, string Resource);